using System;
using System.Collections.Generic;
using System.Text;

namespace Msrp.Message
{
    public class ByteRange
    {
        public ByteRange()
        {
        }

        public ByteRange(long from, long to, long total)
        {
            m_from = from;
            m_to = to;
            m_total = total;
        }

        public bool parse(string fByteRange)
        {
            string[] tokens = fByteRange.Split("-/".ToCharArray());
            if(tokens.Length != 3)
            {
                return false;
            }

            // parse from 
            if (false == Int64.TryParse(tokens[0], out m_from))
            {
                return false;
            }

            // parse to
            if (false == Int64.TryParse(tokens[1], out m_to))
            {
                if (tokens[1] == "*")
                {
                    m_toIsUnknown = true;
                }
                else
                {
                    return false;
                }
            }

            // parse total
            if (false == Int64.TryParse(tokens[2], out m_total))
            {
                if (tokens[1] == "*")
                {
                    m_totalIsUnknown = true;
                }
                else
                {
                    return false;
                }
            }
            return true;
        }

        public string getByteRangeStr()
        {
            StringBuilder sb = new StringBuilder(64);

            sb.Append(m_from);
            sb.Append('-');

            if (true == m_toIsUnknown)
            {
                sb.Append('*');
            } 
            else
            {

                sb.Append(m_to);
            }
            sb.Append('/');

            if (true == m_totalIsUnknown)
            {
                sb.Append('*');
            }
            else
            {
                sb.Append(m_total);
            }
            return sb.ToString();
        }
        
        public long getSize()
        {
            if(m_to == 0 && m_from == 1)
            {
                return 0;
            }
            if (true == m_toIsUnknown)
            {
                return -1;
            }
            return m_to = m_from;
        }

        private long m_from = 1;
        private long m_to = 0;
        private bool m_toIsUnknown = false;
        private long m_total = 0;
        private bool m_totalIsUnknown = false;
    }
}
